package com.writing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.writing.entity.Event;
import com.writing.mapper.EventMapper;
import com.writing.service.EventService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 事件Service实现类
 */
@Service
public class EventServiceImpl extends ServiceImpl<EventMapper, Event> implements EventService {

    @Override
    public List<Event> getEventsByNovelId(Long novelId) {
        return this.list(new LambdaQueryWrapper<Event>()
                .eq(Event::getNovelId, novelId)
                .orderByDesc(Event::getCreatedAt));
    }

    @Override
    public Event getEventById(Long eventId, Long novelId) {
        return this.getOne(new LambdaQueryWrapper<Event>()
                .eq(Event::getId, eventId)
                .eq(Event::getNovelId, novelId));
    }

    @Override
    public Event createEvent(Event event) {
        // 设置默认重要性
        if (event.getImportance() == null) {
            event.setImportance("normal");
        }

        this.save(event);
        return event;
    }

    @Override
    public Event updateEvent(Event event) {
        // 验证事件是否存在
        Event existingEvent = this.getOne(new LambdaQueryWrapper<Event>()
                .eq(Event::getId, event.getId())
                .eq(Event::getNovelId, event.getNovelId()));

        if (existingEvent == null) {
            throw new RuntimeException("事件不存在");
        }

        this.updateById(event);
        return event;
    }

    @Override
    public boolean deleteEvent(Long eventId, Long novelId) {
        Event event = getEventById(eventId, novelId);
        if (event == null) {
            throw new RuntimeException("事件不存在");
        }

        return this.removeById(eventId);
    }

    @Override
    public List<Event> getEventsByImportance(Long novelId, String importance) {
        return this.list(new LambdaQueryWrapper<Event>()
                .eq(Event::getNovelId, novelId)
                .eq(Event::getImportance, importance)
                .orderByDesc(Event::getCreatedAt));
    }

    @Override
    public List<Event> getEventsByChapter(Long novelId, String chapter) {
        return this.list(new LambdaQueryWrapper<Event>()
                .eq(Event::getNovelId, novelId)
                .eq(Event::getChapter, chapter)
                .orderByDesc(Event::getCreatedAt));
    }
}
